import React, { useMemo } from 'react';
import { NodeProps } from 'reactflow';
import { useContextSelector } from 'use-context-selector';

import { t } from '@/locales/i18n';
import { FlowNodeOutputTypeEnum } from '@/types/workflow/constant';
import { FlowNodeItemType } from '@/types/workflow/node';

import { WorkflowContext } from '../../context';

import NodeCard from './render/NodeCard';
import RenderInput from './render/RenderInput';
import RenderOutput from './render/RenderOutput';
import RenderToolInput from './render/RenderToolInput';

const NodeNoFolde = ({
  data,
  selected,
  minW = '350px',
  maxW = '600px',
}: NodeProps<FlowNodeItemType> & { minW?: string | number; maxW?: string | number }) => {
  const splitToolInputs = useContextSelector(WorkflowContext, (ctx) => ctx.splitToolInputs);
  const { nodeId, inputs, outputs } = data;

  const Render = useMemo(() => {
    const { isTool, commonInputs } = splitToolInputs(inputs, nodeId);
    const filterHiddenInputs = commonInputs.filter((item) => true);
    const requiredInputs = filterHiddenInputs.filter((item) => item.required);

    // const { invalidCount } = checkInputsValidCount(requiredInputs);

    const requireText = requiredInputs
      .filter((item) => item.label !== '')
      .map((item) => t(item.label as any))
      .join('，');

    const optionalInputs = filterHiddenInputs.filter(
      (item) => !item.required || item.canEdit === true,
    );

    return (
      <NodeCard minW={minW} maxW={maxW} selected={selected} {...data}>
        <div className="flex flex-col gap-2 p-2">
          {/* Request Configuration */}
          <div>{isTool && <RenderToolInput nodeId={nodeId} inputs={inputs} />}</div>
          {requiredInputs.length > 0 && (
            <RenderInput nodeId={nodeId} flowInputList={requiredInputs} />
          )}

          <div className="">
            {optionalInputs.length > 0 && (
              <RenderInput nodeId={nodeId} flowInputList={optionalInputs} />
            )}
          </div>

          {outputs.filter((output) => output.type !== FlowNodeOutputTypeEnum.hidden).length > 0 && (
            <RenderOutput nodeId={nodeId} flowOutputList={outputs} />
          )}
        </div>
      </NodeCard>
    );
  }, [splitToolInputs, inputs, nodeId, minW, maxW, selected, data, outputs]);

  return Render;
};

export default React.memo(NodeNoFolde);
